package com.example.demo.service;

import com.example.demo.mapper.ArticleMapper;
import com.example.demo.mapper.CategoryMapper;
import com.example.demo.pojo.Article;
import com.example.demo.pojo.Category;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class ArticleService {
    @Autowired
    public ArticleMapper articleMapper;
    @Autowired
    public CategoryMapper categoryMapper;

    public Article select(int id){
        Article  article=articleMapper.selectByPrimaryKey(id);
        return article;
    }

    public void insert(Article article){
        Category category=categoryMapper.selectByPrimaryKey(article.getCategory_id());
        if (category== null){//判断是否存在对应的栏目
            throw new RuntimeException("栏目不存在");
        }else articleMapper.insert(article);
    }

    public void delete(int id){
        articleMapper.deleteByPrimaryKey(id);
    }

    public void update(Article article){
        articleMapper.updateByPrimaryKey(article);
    }

    public PageInfo findByPage(int size, int page){
        PageHelper.startPage(page,size);//分页

        List<Article> articles = articleMapper.selectAll();//查询指定页码的数据

        PageInfo PageInfo = new PageInfo<>(articles);//将数据封装
        return PageInfo;
    }


    public PageInfo selectByPage(int page,int size,String author,String title){
        PageHelper.startPage(page,size);
        /**
         * 分4种情况
         * 1.如果作者和标题都为空则查询所有
         * 2.如果作者和标题都不为空，则查询任意一个中包含的信息
         * 3.如果作者为空，标题不为空
         * 4.如果标题为空，作者不为空
         */
       /* if(author==null){
            author="";
        }
        if (title==null){
            title="";
        }*/
        author=author==null?"":author;
        title=title==null?"":title;

        Example example=new Example(Article.class);
        example.createCriteria()
                .andLike("author","%"+author+"%")
                .andLike("title","%"+title+"%");
        List<Article> articles = articleMapper.selectByExample(example);
        return new PageInfo(articles);
    }

}
